//
//  ReceiptAddressEditViewController.m
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/3/12.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "ReceiptAddressEditViewController.h"
#import "AddressListModel.h"
#import "TPKeyboardAvoidingScrollView.h"
#define PROVINCE_COMPONENT  0
#define CITY_COMPONENT      1
#define DISTRICT_COMPONENT  2

@interface ReceiptAddressEditViewController ()<UIPickerViewDataSource, UIPickerViewDelegate, UITextViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *idNumberTextFeild;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *areaTextField;
@property (weak, nonatomic) IBOutlet UIView *areaMarkView;
@property (weak, nonatomic) IBOutlet UITextView *detailAddressTextView;
@property (weak, nonatomic) IBOutlet UILabel *detailAddressLabel;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *defaultAddressBtn;

@property (nonatomic, strong) UIPickerView *areaPickerView;
@property (nonatomic, strong) UIView *areaPickerViewContainer;
@property (nonatomic, strong) UIButton *selectAreaInfoBtn;

@property(nonatomic, strong) AreaModel *areaModel;
@property(nonatomic, strong) NSArray *province;
@property(nonatomic, strong) NSArray *city;
@property(nonatomic, strong) NSArray *district;
@property(nonatomic, copy) NSString *selectedProvince;
@property(nonatomic, copy)NSString *cityId;
@property(nonatomic, copy)NSString *provinceId;
@property(nonatomic, copy) NSString *zone;
@property(nonatomic, assign) BOOL isDefault;
@property(nonatomic, strong) AddressSubModel *addressModel;
@end

@implementation ReceiptAddressEditViewController

- (id)initWithAddressInfo:(AddressSubModel *)addressModel {
    if (self = [super init]) {
        self.addressModel = addressModel;
        self.isDefault = self.addressModel.is_default;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNaviLeftButton];
    [self setNaviTitle:@"收货地址管理"];
    self.confirmBtn.layer.cornerRadius = 24.f;
    self.detailAddressTextView.layer.borderColor = [UIColor colorWithRGB:0xe1e1e1].CGColor;
    self.detailAddressTextView.layer.cornerRadius = 4;
    self.detailAddressTextView.layer.borderWidth = 1.f;
    self.detailAddressTextView.returnKeyType = UIReturnKeyDone;
    self.nameTextField.returnKeyType=UIReturnKeyDone;
    self.idNumberTextFeild.returnKeyType=UIReturnKeyDone;
    self.phoneTextField.returnKeyType=UIReturnKeyDone;
    self.areaTextField.returnKeyType=UIReturnKeyDone;
    [self.areaMarkView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(areaSelectAction:)]];
    self.detailAddressTextView.delegate = self;
    self.nameTextField.delegate = self;
    self.idNumberTextFeild.delegate = self;
    self.phoneTextField.delegate = self;
    self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, self.defaultAddressBtn.bottom + 20.f);
    [self getAreaList];
    if (self.addressModel) {
        [self updateAddressInfo];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)getAreaList {
    __weak typeof(self) weakSelf = self;
    [ApiClient getProvinceAndCityList:^(AreaModel *model, NSString *path) {
        if ([model.status isEqual:@(1)]) {
            weakSelf.areaModel = model;
            weakSelf.province = [[NSArray alloc] initWithArray: self.areaModel.data.provinces];
            ProvinceModel *province = [weakSelf getObjectFromArray:weakSelf.province forIndex:0];
            if (province) {
                weakSelf.city = [[NSArray alloc] initWithArray:province.cities];
                CityModel *city = [weakSelf getObjectFromArray:weakSelf.city forIndex:0];
                if (city) {
                    weakSelf.district = city.zones;
                } else {
                    weakSelf.district = nil;
                }
            } else {
                weakSelf.city = nil;
            }
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

- (void)updateAddressInfo {
    self.nameTextField.text = self.addressModel.firstname;
    self.phoneTextField.text = self.addressModel.telephone;
    self.idNumberTextFeild.text = self.addressModel.id_number;
    self.detailAddressTextView.text = self.addressModel.address;
    self.areaTextField.text = self.addressModel.formatted_address;
    self.provinceId = self.addressModel.province_id;
    self.cityId = self.addressModel.city_id;
    self.zone = self.addressModel.zone;
    self.detailAddressLabel.text = @"";
    if (self.isDefault) {
        [self.defaultAddressBtn setImage:[UIImage imageNamed:@"btn_select_selectd"] forState:UIControlStateNormal];
    } else {
        [self.defaultAddressBtn setImage:[UIImage imageNamed:@"btn_select_nor"] forState:UIControlStateNormal];
    }
}

- (UIPickerView *)areaPickerView {
    if (!_areaPickerView) {
        _areaPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 15, self.view.width, 200.f)];
        _areaPickerView.backgroundColor = [UIColor whiteColor];
        _areaPickerView.dataSource = self;
        _areaPickerView.delegate = self;
    }
    return _areaPickerView;
}

- (UIView *)areaPickerViewContainer {
    if (!_areaPickerViewContainer) {
        _areaPickerViewContainer = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 220.f, self.view.width, 220.f)];
        _areaPickerViewContainer.backgroundColor = [UIColor whiteColor];
        [_areaPickerViewContainer addSubview:self.areaPickerView];
        [_areaPickerViewContainer addSubview:self.selectAreaInfoBtn];
    }
    return _areaPickerViewContainer;
}

- (UIButton *)selectAreaInfoBtn {
    if (!_selectAreaInfoBtn) {
        _selectAreaInfoBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.width - 60.f, 10, 50, 20)];
        [_selectAreaInfoBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_selectAreaInfoBtn addTarget:self action:@selector(selectDoneAction:) forControlEvents:UIControlEventTouchUpInside];
        [_selectAreaInfoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    return _selectAreaInfoBtn;
}

- (IBAction)setDefualtAddressAction:(id)sender {
    self.isDefault = !self.isDefault;
    if (self.isDefault) {
        [self.defaultAddressBtn setImage:[UIImage imageNamed:@"btn_select_selectd"] forState:UIControlStateNormal];
    } else {
        [self.defaultAddressBtn setImage:[UIImage imageNamed:@"btn_select_nor"] forState:UIControlStateNormal];
    }
}

- (IBAction)confirmEditAction:(id)sender {
    NSString *name = self.nameTextField.text;
    NSString *idNumber = self.idNumberTextFeild.text;
    NSString *telephone = self.phoneTextField.text;
    NSString *detailAddress = self.detailAddressTextView.text;
    NSString *areaInfo = self.areaTextField.text;
    if (name.length <= 0) {
        [[LKDHud shareHud] showtip:@"请输入姓名"];
        return;
    }
    if (idNumber.length <= 0) {
        [[LKDHud shareHud] showtip:@"请输入身份证号"];
        return;
    }
    if (telephone.length <= 0) {
        [[LKDHud shareHud] showtip:@"请输入手机号"];
        return;
    }
    if (![telephone isMobileNumber]) {
        [[LKDHud shareHud] showtip:@"请输入正确的手机号"];
        return;
    }

    if (areaInfo.length <= 0) {
        [[LKDHud shareHud] showtip:@"请选择地区"];
        return;
    }
    if (detailAddress.length <= 0 ) {
        [[LKDHud shareHud] showtip:@"请输入详细地址"];
        return;
    }
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    if (self.addressModel.address_id) {
        [paramDict setObject:self.addressModel.address_id forKey:@"address_id"];
    }
    [paramDict setObject:name forKey:@"firstname"];
    [paramDict setObject:idNumber forKey:@"id_number"];
    [paramDict setObject:telephone forKey:@"telephone"];
    [paramDict setObject:self.provinceId forKey:@"province_id"];
    [paramDict setObject:self.cityId forKey:@"city_id"];
    [paramDict setObject:self.zone forKey:@"zone"];
    [paramDict setObject:detailAddress forKey:@"address"];
    [paramDict setObject:@(self.isDefault) forKey:@"default"];
    __weak typeof(self)weakSelf = self;
    [[LKDHud shareHud] showLoadingView];
    [ApiClient addAddress:paramDict didFinishLoaded:^(KXJson *json, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        NSString *status = [json getStringForKey:@"status"];
        if ([status isEqualToString:@"1"]) {
            [[LKDHud shareHud] showtip:@"成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
    }];
}

- (void)areaSelectAction:(id)sender {
    [self.nameTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
    [self.detailAddressTextView resignFirstResponder];
    [self.idNumberTextFeild resignFirstResponder];
    [self.view addSubview:self.areaPickerViewContainer];
}

- (void)selectDoneAction:(id)sender {
    NSInteger provinceIndex = [self.areaPickerView selectedRowInComponent: PROVINCE_COMPONENT];
    NSInteger cityIndex = [self.areaPickerView selectedRowInComponent: CITY_COMPONENT];
    NSInteger districtIndex = [self.areaPickerView selectedRowInComponent: DISTRICT_COMPONENT];
    
    ProvinceModel *provinceModel = [self getObjectFromArray:self.province forIndex:provinceIndex];
    CityModel *cityModel = [self getObjectFromArray:self.city forIndex:cityIndex];
    ZoneModel *districtModel = [self getObjectFromArray:self.district forIndex:districtIndex];
    self.provinceId = provinceModel ? provinceModel.province_id : @"";
    self.cityId = cityModel ? cityModel.city_id : @"";
    self.zone = districtModel ? districtModel.name : @"";
    NSString *provinceStr = provinceModel ? provinceModel.name : @"";
    NSString *cityStr = cityModel ? cityModel.name : @"";
    NSString *districtStr = districtModel ? districtModel.name : @"";
    if ([provinceStr isEqualToString: cityStr] && [cityStr isEqualToString: districtStr]) {
        cityStr = @"";
        districtStr = @"";
    }
    else if ([cityStr isEqualToString: districtStr]) {
        districtStr = @"";
    }
    
    NSString *showMsg = [NSString stringWithFormat: @"%@ %@ %@", provinceStr, cityStr, districtStr];
    [self.areaPickerViewContainer removeFromSuperview];
    self.areaTextField.text = showMsg;
}

#pragma --mark textview delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length == 0) {
        self.detailAddressLabel.text = @"详细地址（必填）";
    }else{
        self.detailAddressLabel.text = @"";
    }
}

#pragma --mark textfield delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger textLength = textField.text.length;
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }

    if([string isEqualToString:@""]) {
        return YES;
    }
    if ([textField isEqual:self.phoneTextField] && textLength >= 11) {
        [[LKDHud shareHud] showtip:@"手机号码不得超过11位"];
        textField.text = [textField.text substringToIndex:11];
        return NO;
    }
    if ([textField isEqual:self.idNumberTextFeild] && textLength >= 18) {
        [[LKDHud shareHud] showtip:@"身份证号码不得超过18位"];
        textField.text = [textField.text substringToIndex:18];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSInteger textLength = textField.text.length;
    if ([textField isEqual:self.nameTextField] && textLength >= 11) {
        textField.text = [textField.text substringToIndex:10];
        [[LKDHud shareHud] showtip:@"姓名不能超过10位"];
    }
    if ([textField isEqual:self.phoneTextField] && textLength >= 12) {
        [[LKDHud shareHud] showtip:@"手机号码不得超过11位"];
        textField.text = [textField.text substringToIndex:11];
    }
    if ([textField isEqual:self.idNumberTextFeild] && textLength >= 19) {
        [[LKDHud shareHud] showtip:@"身份证号码不得超过18位"];
        textField.text = [textField.text substringToIndex:18];
    }
    return YES;
}

#pragma --mark UIDatePickerViewDelegate and DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == PROVINCE_COMPONENT) {
        return [self.province count];
    }
    else if (component == CITY_COMPONENT) {
        return [self.city count];
    }
    else {
        return [self.district count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == PROVINCE_COMPONENT) {
        if (self.province.count <= 0) {
            return @"";
        }
        ProvinceModel *province = [self.province objectAtIndex: row];
        return province.name;
    }
    else if (component == CITY_COMPONENT) {
        if (self.city.count <= 0) {
            return @"";
        }
        CityModel *city = [self.city objectAtIndex:row];
        return city.name;
    }
    else {
        if (self.district.count <= 0) {
            return @"";
        }
        ZoneModel *zone = [self.district objectAtIndex:row];
        return zone.name;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == PROVINCE_COMPONENT) {
        ProvinceModel *province = [self getObjectFromArray:self.province forIndex:row];
        if (province) {
            self.selectedProvince = province.name;
            self.city = [[NSArray alloc] initWithArray:province.cities];
            CityModel *city = [self getObjectFromArray:self.city forIndex:0];
            if (city) {
                self.district = city.zones;
            } else {
                self.district = nil;
            }
        } else {
            self.city = nil;
        }
        [self.areaPickerView selectRow: 0 inComponent: CITY_COMPONENT animated: YES];
        [self.areaPickerView selectRow: 0 inComponent: DISTRICT_COMPONENT animated: YES];
        [self.areaPickerView reloadComponent: CITY_COMPONENT];
        [self.areaPickerView reloadComponent: DISTRICT_COMPONENT];
        
    }
    else if (component == CITY_COMPONENT) {
        CityModel *city = [self getObjectFromArray:self.city forIndex:row];
        if (city) {
            self.district = city.zones;
        }
        [self.areaPickerView selectRow: 0 inComponent: DISTRICT_COMPONENT animated: YES];
        [self.areaPickerView reloadComponent: DISTRICT_COMPONENT];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == PROVINCE_COMPONENT) {
        return 80;
    }
    else if (component == CITY_COMPONENT) {
        return 100;
    }
    else {
        return 115;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *myView = nil;
    
    if (component == PROVINCE_COMPONENT) {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 78, 30)];
        myView.textAlignment = NSTextAlignmentCenter;
        if ([self getObjectFromArray:self.province forIndex:row]) {
            myView.text = ((ProvinceModel *)[self getObjectFromArray:self.province forIndex:row]).name;
        } else {
            myView.text = @"";
        }
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    else if (component == CITY_COMPONENT) {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 95, 30)];
        myView.textAlignment = NSTextAlignmentCenter;
        if ([self getObjectFromArray:self.city forIndex:row]) {
            myView.text = ((CityModel *)[self getObjectFromArray:self.city forIndex:row]).name;
        } else {
            myView.text = @"";
        }
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    else {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 110, 30)];
        myView.textAlignment = NSTextAlignmentCenter;
        if ([self getObjectFromArray:self.district forIndex:row]) {
            myView.text = ((ZoneModel *)[self getObjectFromArray:self.district forIndex:row]).name;
        } else {
            myView.text = @"";
        }
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    return myView;
}

- (id)getObjectFromArray:(NSArray *)array forIndex:(NSInteger)index {
    if (array.count <= 0) {
        return nil;
    }
    if (index > array.count) {
        return nil;
    }
    return [array objectAtIndex:index];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
